package com.haoyeteng.sxbd.modular.system.controller;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.naming.NoPermissionException;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.haoyeteng.sxbd.config.properties.SxbdProperties;
import com.haoyeteng.sxbd.core.base.controller.BaseController;
import com.haoyeteng.sxbd.core.base.model.ResponseResult;
import com.haoyeteng.sxbd.core.base.tips.Tip;
import com.haoyeteng.sxbd.core.common.annotion.BussinessLog;
import com.haoyeteng.sxbd.core.common.annotion.Permission;
import com.haoyeteng.sxbd.core.common.constant.Const;
import com.haoyeteng.sxbd.core.common.constant.dictmap.AdminDict;
import com.haoyeteng.sxbd.core.common.constant.factory.PageFactory;
import com.haoyeteng.sxbd.core.common.constant.state.ManagerStatus;
import com.haoyeteng.sxbd.core.common.exception.BizExceptionEnum;
import com.haoyeteng.sxbd.core.constant.DeleteFlag;
import com.haoyeteng.sxbd.core.db.Db;
import com.haoyeteng.sxbd.core.exception.SxbdException;
import com.haoyeteng.sxbd.core.log.LogObjectHolder;
import com.haoyeteng.sxbd.core.shiro.ShiroAdmin;
import com.haoyeteng.sxbd.core.shiro.ShiroKit;
import com.haoyeteng.sxbd.core.util.ToolUtil;
import com.haoyeteng.sxbd.modular.system.dao.AdminMapper;
import com.haoyeteng.sxbd.modular.system.factory.AdminFactory;
import com.haoyeteng.sxbd.modular.system.model.Admin;
import com.haoyeteng.sxbd.modular.system.model.Role;
import com.haoyeteng.sxbd.modular.system.service.IAdminService;
import com.haoyeteng.sxbd.modular.system.service.IRoleService;
import com.haoyeteng.sxbd.modular.system.transfer.AdminDto;
import com.haoyeteng.sxbd.modular.system.warpper.AdminWarpper;

/**
 * 系统管理员控制器
 *
 * @author zhanglixiang
 * @Date 2017年1月11日 下午1:08:17
 */
@Controller
@RequestMapping("/admin")
public class AdminController extends BaseController {

    private static String PREFIX = "/system/admin/";

    @Autowired
    private SxbdProperties sxbdProperties;

    @Autowired
    private IAdminService adminService;
    
    @Autowired
    private IRoleService roleService;

    /**
     * 跳转到查看管理员列表的页面
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "admin.html";
    }

    /**
     * 跳转到查看管理员列表的页面
     */
    @RequestMapping("/admin_add")
    public String add(Model model) {
    	EntityWrapper<Role> ew = new EntityWrapper<Role>();
    	List<Role> roleList = roleService.selectList(ew.ne("id", Const.ADMIN_ID).orderBy("num"));
    	model.addAttribute("roleList", roleList);
        return PREFIX + "admin_add.html";
    }

    /**
     * 跳转到角色分配页面
     */
    //@RequiresPermissions("/mgr/role_assign")  //利用shiro自带的权限检查
    @Permission
    @RequestMapping("/role_assign/{adminId}")
    public String roleAssign(@PathVariable Integer adminId, Model model) {
        if (ToolUtil.isEmpty(adminId)) {
            throw new SxbdException(BizExceptionEnum.REQUEST_NULL);
        }
        Admin admin = (Admin) Db.create(AdminMapper.class).selectOneByCon("id", adminId);
        model.addAttribute("adminId", adminId);
        model.addAttribute("adminAccount", admin.getAccount());
        return PREFIX + "admin_roleassign.html";
    }

    /**
     * 跳转到编辑管理员页面
     */
    @RequestMapping("/admin_update/{adminId}")
    public String adminUpdate(@PathVariable Integer adminId, Model model) {
		Admin admin = adminService.selectById(adminId);
		model.addAttribute("admin", admin);
		EntityWrapper<Role> ew = new EntityWrapper<Role>();
    	List<Role> roleList = roleService.selectList(ew.ne("id", Const.ADMIN_ID).orderBy("num"));
    	model.addAttribute("roleList", roleList);
        return PREFIX + "admin_update.html";
    }


    /**
     * 跳转到修改密码界面
     */
    @RequestMapping("/admin_password")
    public String chPwd(Model model) {
    	Admin admin = adminService.selectById(ShiroKit.getAdmin().getId());
		model.addAttribute("admin", admin);
        return PREFIX + "admin_password.html";
    }

    /**
     * 修改当前用户的密码
     */
    @RequestMapping("/password/update")
    @ResponseBody
    public Object changePwd(@RequestParam String oldPwd, @RequestParam String newPwd, @RequestParam String rePwd) {
        if (!newPwd.equals(rePwd)) {
            throw new SxbdException(BizExceptionEnum.TWO_PWD_NOT_MATCH);
        }
        Integer adminId = ShiroKit.getAdmin().getId();
        Admin admin = adminService.selectById(adminId);
        String oldMd5 = ShiroKit.md5(oldPwd, admin.getSalt());
        if (admin.getPassword().equals(oldMd5)) {
            String newMd5 = ShiroKit.md5(newPwd.trim(), admin.getSalt());
            admin.setPassword(newMd5);
            admin.updateById();
            return SUCCESS_TIP;
        } else {
            throw new SxbdException(BizExceptionEnum.OLD_PWD_NOT_RIGHT);
        }
    }

    /**
     * 查询管理员列表
     */
    @RequestMapping("/list")
    @Permission
    @ResponseBody
    public ResponseResult<Object> list(@RequestParam(required = false) String name, @RequestParam(required = false) String account) {
        
        ResponseResult<Object> result = new ResponseResult<Object>();
    	Page<Admin> page = new PageFactory<Admin>().defaultPage(); 
    	List<Map<String, Object>> admins = adminService.selectAdmins(page, name, account);
        result.setData(new AdminWarpper(admins).warp());
 		result.setCount(page.getTotal());
     	result.setCode(SUCCESS_TIP.getCode());
     	result.setMsg(SUCCESS_TIP.getMessage());
 		return result;
    	/*if (ShiroKit.isAdmin()) {
            List<Map<String, Object>> admins = adminService.selectAdmins(null, name, beginTime, endTime, deptid);
            return new AdminWarpper(admins).warp();
        } else {
            DataScope dataScope = new DataScope(ShiroKit.getDeptDataScope());
            List<Map<String, Object>> admins = adminService.selectAdmins(dataScope, name, beginTime, endTime, deptid);
            return new AdminWarpper(admins).warp();
        }*/
    }


    /**
     * 添加管理员
     */
    @RequestMapping("/add")
    @BussinessLog(value = "添加管理员", key = "account", dict = AdminDict.class)
    @Permission//(Const.ADMIN_NAME)
    @ResponseBody
    public Tip add(@Valid AdminDto admin, String rePassword, BindingResult result) {
        if (result.hasErrors()) {
            throw new SxbdException(BizExceptionEnum.REQUEST_NULL);
        }
        // 判断账号是否重复
        Admin theAdmin = adminService.getByAccount(admin.getAccount());
        if (theAdmin != null) {
            throw new SxbdException(BizExceptionEnum.ADMIN_ALREADY_REG);
        }
        
        if (!admin.getPassword().equals(rePassword)) {
            throw new SxbdException(BizExceptionEnum.TWO_PWD_NOT_MATCH);
        }
        
        //判断邮箱是否重复
        Admin tempAdmin = adminService.selectOne(new EntityWrapper<Admin>().eq("email", admin.getEmail()));
        if (tempAdmin != null) {
            throw new SxbdException(400, "邮箱已存在");
        }

        // 完善账号信息
        admin.setSalt(ShiroKit.getRandomSalt(5));
        admin.setPassword(ShiroKit.md5(admin.getPassword(), admin.getSalt()));
        admin.setStatus(ManagerStatus.OK.getCode());
        admin.setCreatetime(new Date());
        admin.setFlag(DeleteFlag.OK.getCode());
        this.adminService.insert(AdminFactory.createAdmin(admin));
        return SUCCESS_TIP;
    }

    /**
     * 修改管理员
     *
     * @throws NoPermissionException
     */
    @RequestMapping("/update")
    @BussinessLog(value = "修改管理员", key = "account", dict = AdminDict.class)
    @ResponseBody
    public Tip update(@Valid AdminDto admin, BindingResult result) throws NoPermissionException {
        System.out.println("admin========"+admin);
    	if (result.hasErrors()) {
            throw new SxbdException(BizExceptionEnum.REQUEST_NULL);
        }
        if (ShiroKit.hasRole(Const.ADMIN_NAME)) {
            this.adminService.updateById(AdminFactory.createAdmin(admin));
            return SUCCESS_TIP;
        } else {
            //assertAuth(admin.getId());
            ShiroAdmin shiroAdmin = ShiroKit.getAdmin();
            if (shiroAdmin.getId().equals(admin.getId())) {
                this.adminService.updateById(AdminFactory.createAdmin(admin));
                return SUCCESS_TIP;
            } else {
                throw new SxbdException(BizExceptionEnum.NO_PERMITION);
            }
        }
    }

    /**
     * 删除管理员（逻辑删除）
     */
    @RequestMapping("/delete")
    @BussinessLog(value = "删除管理员", key = "adminId", dict = AdminDict.class)
    @Permission
    @ResponseBody
    public Tip delete(@RequestParam Integer adminId) {
        if (ToolUtil.isEmpty(adminId)) {
            throw new SxbdException(BizExceptionEnum.REQUEST_NULL);
        }
        //不能删除超级管理员
        if (adminId.equals(Const.ADMIN_ID)) {
            throw new SxbdException(BizExceptionEnum.CANT_DELETE_ADMIN);
        }
        //assertAuth(adminId);
        //this.adminService.setStatus(adminId, ManagerStatus.DELETED.getCode());
        adminService.deleteById(adminId);
        return SUCCESS_TIP;
    }

    /**
     * 查看管理员详情
     */
    @RequestMapping("/view/{adminId}")
    @ResponseBody
    public Admin view(@PathVariable Integer adminId) {
        if (ToolUtil.isEmpty(adminId)) {
            throw new SxbdException(BizExceptionEnum.REQUEST_NULL);
        }
        //assertAuth(adminId);
        return this.adminService.selectById(adminId);
    }

    /**
     * 重置管理员的密码
     */
    @RequestMapping("/reset")
    @BussinessLog(value = "重置管理员密码", key = "adminId", dict = AdminDict.class)
    @Permission//(Const.ADMIN_NAME)
    @ResponseBody
    public Tip reset(@RequestParam Integer adminId) {
        if (ToolUtil.isEmpty(adminId)) {
            throw new SxbdException(BizExceptionEnum.REQUEST_NULL);
        }
        //assertAuth(adminId);
        Admin admin = this.adminService.selectById(adminId);
        admin.setSalt(ShiroKit.getRandomSalt(5));
        admin.setPassword(ShiroKit.md5(Const.DEFAULT_PWD, admin.getSalt()));
        this.adminService.updateById(admin);
        return SUCCESS_TIP;
    }

    /**
     * 冻结用户
     */
    @RequestMapping("/freeze")
    @BussinessLog(value = "冻结用户", key = "adminId", dict = AdminDict.class)
    @Permission//(Const.ADMIN_NAME)
    @ResponseBody
    public Tip freeze(@RequestParam Integer adminId) {
        if (ToolUtil.isEmpty(adminId)) {
            throw new SxbdException(BizExceptionEnum.REQUEST_NULL);
        }
        //不能冻结超级管理员
        if (adminId.equals(Const.ADMIN_ID)) {
            throw new SxbdException(BizExceptionEnum.CANT_FREEZE_ADMIN);
        }
        //assertAuth(adminId);
        this.adminService.setStatus(adminId, ManagerStatus.FREEZED.getCode());
        return SUCCESS_TIP;
    }

    /**
     * 解除冻结用户
     */
    @RequestMapping("/unfreeze")
    @BussinessLog(value = "解除冻结用户", key = "adminId", dict = AdminDict.class)
    @Permission//(Const.ADMIN_NAME)
    @ResponseBody
    public Tip unfreeze(@RequestParam Integer adminId) {
        if (ToolUtil.isEmpty(adminId)) {
            throw new SxbdException(BizExceptionEnum.REQUEST_NULL);
        }
        //assertAuth(adminId);
        this.adminService.setStatus(adminId, ManagerStatus.OK.getCode());
        return SUCCESS_TIP;
    }

    /**
     * 分配角色
     */
    @RequestMapping("/setRole")
    @BussinessLog(value = "分配角色", key = "adminId,roleIds", dict = AdminDict.class)
    @Permission//(Const.ADMIN_NAME)
    @ResponseBody
    public Tip setRole(@RequestParam("adminId") Integer adminId, @RequestParam("roleIds") String roleIds) {
        if (ToolUtil.isOneEmpty(adminId, roleIds)) {
            throw new SxbdException(BizExceptionEnum.REQUEST_NULL);
        }
        //不能修改超级管理员
        if (adminId.equals(Const.ADMIN_ID)) {
            throw new SxbdException(BizExceptionEnum.CANT_CHANGE_ADMIN);
        }
        //assertAuth(adminId);
        this.adminService.setRoles(adminId, roleIds);
        return SUCCESS_TIP;
    }

    /**
     * 上传图片(上传到项目的webapp/static/img)
     */
    @RequestMapping(method = RequestMethod.POST, path = "/upload")
    @ResponseBody
    public String upload(@RequestPart("file") MultipartFile picture) {
        String pictureName = UUID.randomUUID().toString() + ".jpg";
        try {
            String fileSavePath = sxbdProperties.getFileUploadPath();
            picture.transferTo(new File(fileSavePath + pictureName));
        } catch (Exception e) {
            throw new SxbdException(BizExceptionEnum.UPLOAD_ERROR);
        }
        return pictureName;
    }

    /**
     * 判断当前登录的用户是否有操作这个用户的权限
     */
    /*private void assertAuth(Integer adminId) {
    	return;
        if (ShiroKit.isAdmin()) {
            return;
        }
        List<Integer> deptDataScope = ShiroKit.getDeptDataScope();
        Admin admin = this.adminService.selectById(adminId);
        Integer deptid = admin.getDeptid();
        if (deptDataScope.contains(deptid)) {
            return;
        } else {
            throw new ComacException(BizExceptionEnum.NO_PERMITION);
        }

    }*/
    
    /**
     * 跳转到用户信息修改页面
     * @param model
     * @return
     */
    @RequestMapping("/admin_info")
	public String userUpdate(Model model) {
		Integer adminId = ShiroKit.getAdmin().getId();
		Admin admin = adminService.selectById(adminId);
		model.addAttribute("admin", admin);
		return PREFIX + "admin_info.html";
	}
    
    /**
     * 修改用户信息
     * @param email
     * @return
     */
    @RequestMapping("/info")
	@ResponseBody
	public Object info(@RequestParam String email) {
    	Admin adminTemp = adminService.selectOne(new EntityWrapper<Admin>().eq("email", email));
    	if(ToolUtil.isNotEmpty(adminTemp)) {
    		throw new SxbdException(400,"邮箱已存在！");
    	}
		Integer id = ShiroKit.getAdmin().getId();
		Admin admin = adminService.selectById(id);
		admin.setEmail(email);
		adminService.updateById(admin);
		return SUCCESS_TIP;
	}
}
